using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PlacementManager;

public partial class Home_Contacts : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["DivisionID"] == null)
        {
            Response.Redirect("~/Default.aspx");
        }
        //Response.Write("id:" + Request.QueryString["id"]);
        if (!Page.IsPostBack)
        {
            this.txtSearchName.Focus();
            //Response.Write("id:" + Request.QueryString["id"]);
            if (Request.QueryString["id"] != null)
            {
                this.gvContacts.DataSourceID = "odsSingleContact";
            }
            else
            {
                this.gvContacts.DataSourceID = "odsContacts";
            }
        }
        if (Session["ContactSelectedIndex"] != null)
        {
            this.gvContacts.SelectedIndex = Int32.Parse(Session["ContactSelectedIndex"].ToString());
        }
        if (Session["ContactPageIndex"] != null)
        {
            this.gvContacts.PageIndex = Int32.Parse(Session["ContactPageIndex"].ToString());
        }
    }

    #region Contacts GridView Methods
    protected void gvContacts_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.gvContactAttributes.DataBind();
    }
    #endregion

    #region Contact FormView Methods
    protected void fvContact_ItemUpdating(object sender, FormViewUpdateEventArgs e)
    {
        PlacementManager.ContactComponent oContactC = new PlacementManager.ContactComponent();
        PlacementManager.Contact oContact = oContactC.SelectOne(Int32.Parse(this.gvContacts.SelectedValue.ToString()));

        e.NewValues.Add("ContactId", oContact.ContactId);
        e.NewValues.Add("DivisionId", Int32.Parse(Session["DivisionId"].ToString()));
        e.NewValues.Add("IsActive", true);
        e.NewValues.Add("DateCreated", oContact.DateCreated);
        e.NewValues.Add("CreatedBy", oContact.CreatedBy);
        e.NewValues.Add("DateUpdated", DateTime.Now);
        e.NewValues.Add("UpdatedBy", User.Identity.Name);
    }
    protected void fvContact_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
    {
        this.gvContacts.DataBind();
    }
    protected void fvContact_ItemCommand(object sender, FormViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteContact")
        {
            PlacementManager.ContactComponent oContactC = new PlacementManager.ContactComponent();
            PlacementManager.Contact oContact = oContactC.SelectOne(Int32.Parse(this.gvContacts.SelectedDataKey.Value.ToString()));
            oContact.IsActive = false;
            oContactC.Update(oContact);
            this.gvContacts.DataBind();
        }
    }
    #endregion

    #region Contact Numbers Methods
    protected void gvContactNumbers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteContactNumber")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            int contactContactNumberId = Int32.Parse(this.gvContactNumbers.DataKeys[index].Value.ToString());

            PlacementManager.LinkContactContactNumberComponent oLccC = new PlacementManager.LinkContactContactNumberComponent();
            oLccC.Delete(contactContactNumberId);

            this.gvContactNumbers.DataBind();
        }
    }
    protected void btnAddContactNumber_Click(object sender, EventArgs e)
    {
        PlacementManager.ContactNumberComponent oContactNumberC = new PlacementManager.ContactNumberComponent();
        PlacementManager.ContactNumber oContactNumber = new PlacementManager.ContactNumber();
        oContactNumber.ContactNumberTypeId = Int32.Parse(this.ddNewContactNumberType.SelectedValue);
        oContactNumber.ContactNumberValue = this.txtNewContactNumber.Text;
        int contactNumberId = oContactNumberC.Insert(oContactNumber);

        PlacementManager.LinkContactContactNumberComponent oLccnC = new PlacementManager.LinkContactContactNumberComponent();
        PlacementManager.LinkContactContactNumber oLccn = new PlacementManager.LinkContactContactNumber();
        oLccn.ContactId = Int32.Parse(this.gvContacts.SelectedDataKey.Value.ToString());
        oLccn.ContactNumberId = contactNumberId;
        oLccn.CreatedBy = User.Identity.Name;
        oLccn.DateCreated = DateTime.Now;
        oLccn.DateUpdated = DateTime.Now;
        oLccn.IsActive = true;
        oLccn.UpdatedBy = User.Identity.Name;
        oLccnC.Insert(oLccn);

        this.gvContactNumbers.DataBind();

        this.txtNewContactNumber.Text = string.Empty;
    }
    #endregion

    #region Associated Venues Methods
    protected void gvVenueContacts_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteVenueLink")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            int venueContactId = Int32.Parse(this.gvVenueContacts.DataKeys[index].Value.ToString());

            PlacementManager.LinkVenueContactComponent oLvcC = new PlacementManager.LinkVenueContactComponent();
            oLvcC.Delete(venueContactId);

            this.gvVenueContacts.DataBind();
        }
    }
    protected void btnAttachVenue_Click(object sender, EventArgs e)
    {
        PlacementManager.VenueComponent oVenueC = new PlacementManager.VenueComponent();
        PlacementManager.Venue oVenue = oVenueC.SelectOneWVenueName(this.txtVenueName.Text);

        if (oVenue.VenueId > 0)
        {
            PlacementManager.LinkVenueContactComponent oLvcC = new PlacementManager.LinkVenueContactComponent();
            List<PlacementManager.LinkVenueContact> oLvcList = oLvcC.SelectAllWVenueIdContactId(oVenue.VenueId, Int32.Parse(this.gvContacts.SelectedValue.ToString()), "VenueId");

            if (oLvcList.Count == 0)
            {
                PlacementManager.LinkVenueContact oLvc = new PlacementManager.LinkVenueContact();
                oLvc.ContactId = Int32.Parse(this.gvContacts.SelectedDataKey.Value.ToString());
                oLvc.IsActive = true;
                oLvc.CreatedBy = User.Identity.Name;
                oLvc.DateUpdated = DateTime.Now;
                oLvc.DateCreated = DateTime.Now;
                oLvc.IsPrimary = false;
                oLvc.UpdatedBy = User.Identity.Name;
                oLvc.VenueId = oVenue.VenueId;

                oLvcC.Insert(oLvc);
            }
        }

        this.gvVenueContacts.DataBind();
        this.txtVenueName.Text = string.Empty;
    }
    #endregion

    #region Address Methods
    protected void dlAddresses_DeleteCommand(object source, DataListCommandEventArgs e)
    {
        int addressId = Int32.Parse(this.dlAddresses.DataKeys[e.Item.ItemIndex].ToString());
        PlacementManager.LinkContactAddressComponent oLvaC = new LinkContactAddressComponent();
        oLvaC.DeleteAllWAddressId(addressId);
        PlacementManager.AddressComponent oAddressC = new AddressComponent();
        oAddressC.Delete(addressId);

        this.dlAddresses.DataBind();
    }
    protected void dlAddresses_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "MakeAddressPrimary")
        {
            int addressId = Int32.Parse(this.dlAddresses.DataKeys[e.Item.ItemIndex].ToString());
            PlacementManager.AddressComponent oAddressC = new AddressComponent();
            oAddressC.SetContactPrimaryAddress(addressId);
            this.dlAddresses.DataBind();
        }
    }
    protected void btnAddAddress_Click(object sender, EventArgs e)
    {
        //Create some objects that we will use later to save creating them separately
        //A Google Map object so we can try and resolve the coordinates of the address
        PlacementManager.GoogleMap oGM = new PlacementManager.GoogleMap();

        //Get an address string to check for geo-coordinates
        string address = this.txtNewAddress1.Text + ",";
        if (this.txtNewAddress2.Text.Length > 0)
        {
            address += this.txtNewAddress2 + ",";
        }
        address += this.txtNewCity.Text + ", " + this.ddNewState.SelectedItem.Text + ", " + this.ddNewCountry.SelectedItem.Text;

        //Let's try and get the coordinates
        float[] coordinates = oGM.GetLongitudeLatitude(address);

        PlacementManager.AddressComponent oAddressC = new AddressComponent();
        PlacementManager.Address oAddress = new PlacementManager.Address();
        oAddress.Address1 = this.txtNewAddress1.Text;
        oAddress.Address2 = this.txtNewAddress2.Text;
        oAddress.Street = this.txtNewStreet.Text;
        oAddress.City = this.txtNewCity.Text;
        oAddress.CountryId = Int32.Parse(this.ddNewCountry.SelectedValue);
        oAddress.CreatedBy = User.Identity.Name;
        oAddress.DateCreated = DateTime.Now;
        oAddress.DateUpdated = DateTime.Now;
        oAddress.IsActive = true;
        oAddress.IsPostal = this.cbNewAddressIsPostal.Checked;
        oAddress.Latitude = coordinates[1];
        oAddress.Longitude = coordinates[0];
        oAddress.PostCode = txtNewPostCode.Text;
        oAddress.StateId = Int32.Parse(this.ddNewState.SelectedValue);
        oAddress.UpdatedBy = User.Identity.Name;

        int addressId = oAddressC.Insert(oAddress);

        PlacementManager.LinkContactAddressComponent oLcaC = new LinkContactAddressComponent();
        PlacementManager.LinkContactAddress oLca = new LinkContactAddress();

        oLca.AddressId = addressId;
        oLca.ContactId = Int32.Parse(this.gvContacts.SelectedDataKey.Value.ToString());
        oLca.CreatedBy = User.Identity.Name;
        oLca.DateCreated = DateTime.Now;
        oLca.DateUpdated = DateTime.Now;
        oLca.IsActive = true;
        oLca.IsCurrent = true;
        oLca.IsPrimary = this.cbNewAddressIsPrimary.Checked;
        oLca.UpdatedBy = User.Identity.Name;
        oLcaC.Insert(oLca);

        if (this.cbNewAddressIsPrimary.Checked)
        {
            oAddressC.SetContactPrimaryAddress(addressId);
        }

        this.dlAddresses.DataBind();

        this.txtNewAddress1.Text = string.Empty;
        this.txtNewAddress2.Text = string.Empty;
        this.txtNewStreet.Text = string.Empty;
        this.txtNewCity.Text = string.Empty;
        this.txtNewPostCode.Text = string.Empty;
    }
    protected void imgbtnFindPostCode_Click(object sender, ImageClickEventArgs e)
    {
        PlacementManager.Geo_PostcodesComponent oPostCodeC = new Geo_PostcodesComponent();
        PlacementManager.Geo_Postcodes oPostCode = oPostCodeC.SelectOneWTownCode(this.txtNewCity.Text);
        this.txtNewPostCode.Text = oPostCode.Postcode.ToString();
    }
    #endregion

    #region Contact Attribute Methods
    protected void gvContactAttributes_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int contactAttribId = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ContactAttributeID"));


            //Find out if there is a record of the student having this attribute
            PlacementManager.LinkContactAttributeContactComponent oLcacC = new PlacementManager.LinkContactAttributeContactComponent();
            List<PlacementManager.LinkContactAttributeContact> listLcac = oLcacC.SelectAllWContactIdContactAttributeId(Int32.Parse(this.gvContacts.SelectedValue.ToString()), contactAttribId, "ContactId");


            if (listLcac.Count > 0)//The link exists
            {
                PlacementManager.LinkContactAttributeContact oLcac = listLcac[0];
                ((CheckBox)e.Row.FindControl("cbEditContactAttribute")).Checked = oLcac.IsActive;
            }
        }
    }
    protected void btnUpdateAttribute_Click(object sender, EventArgs e)
    {
        int contactAttribId = 0;
        int contactId = Int32.Parse(this.gvContacts.SelectedValue.ToString());
        foreach (GridViewRow gvr in this.gvContactAttributes.Rows)
        {
            CheckBox cbEditContactAttribute = (CheckBox)gvr.FindControl("cbEditContactAttribute");
            contactAttribId = Int32.Parse(this.gvContactAttributes.DataKeys[gvr.RowIndex].Value.ToString());

            PlacementManager.LinkContactAttributeContactComponent oLcacC = new PlacementManager.LinkContactAttributeContactComponent();
            List<PlacementManager.LinkContactAttributeContact> listLcac = oLcacC.SelectAllWContactIdContactAttributeId(contactId, contactAttribId, "ContactId");

            if (listLcac.Count > 0)
            {
                PlacementManager.LinkContactAttributeContact oLcac = listLcac[0];
                oLcac.IsActive = cbEditContactAttribute.Checked;
                oLcac.DateUpdated = DateTime.Now;
                oLcac.UpdatedBy = User.Identity.Name;
                oLcacC.Update(oLcac);
            }
            else
            {
                PlacementManager.LinkContactAttributeContact oLcac = new PlacementManager.LinkContactAttributeContact();
                oLcac.ContactAttributeId = contactAttribId;
                oLcac.ContactId = contactId;
                oLcac.CreatedBy = User.Identity.Name;
                oLcac.DateCreated = DateTime.Now;
                oLcac.DateUpdated = DateTime.Now;
                oLcac.IsActive = cbEditContactAttribute.Checked;
                oLcac.UpdatedBy = User.Identity.Name;
                oLcacC.Insert(oLcac);
            }
        }
        this.gvContactAttributes.DataBind();
    }
    #endregion

    protected void btnInsertContact_Click(object sender, EventArgs e)
    {
        if (this.txtNewContactLastName.Text.Length > 0)
        {
            int existingContactId = 0;
            PlacementManager.ContactComponent oContactC = new PlacementManager.ContactComponent();

            if (this.txtNewContactEmail.Text.Length > 0)//Need to check that the same email doesn't exits already
            {
                PlacementManager.Contact oExistingContact = oContactC.SelectOneWEmailAddress(this.txtNewContactEmail.Text.Trim());
                existingContactId = oExistingContact.ContactId;
            }

            if (existingContactId == 0)
            {
                //Create a new contact
                PlacementManager.Contact oContact = new PlacementManager.Contact();
                oContact.EducatorCurrentRate = 0;
                oContact.Title = this.txtNewContactTitle.Text;
                oContact.CreatedBy = User.Identity.Name;
                oContact.DateCreated = DateTime.Now;
                oContact.DateUpdated = DateTime.Now;
                oContact.DivisionId = Int32.Parse(Session["DivisionId"].ToString());
                oContact.EmailAddress = this.txtNewContactEmail.Text;
                oContact.FirstName = this.txtNewContactFirstName.Text;
                oContact.EducatorTypeId = 1;
                oContact.IsActive = true;
                oContact.JobTitle = this.txtNewContactJobTitle.Text;
                oContact.LastName = this.txtNewContactLastName.Text;
                oContact.UpdatedBy = User.Identity.Name;
                int contactId = oContactC.Insert(oContact);

                //Reset the textfields
                this.txtNewContactTitle.Text = string.Empty;
                this.txtNewContactEmail.Text = string.Empty;
                this.txtNewContactFirstName.Text = string.Empty;
                this.txtNewContactJobTitle.Text = string.Empty;
                this.txtNewContactLastName.Text = string.Empty;

                //Reset the new number field
                this.txtNewContactNumber.Text = string.Empty;

                //Set the search box
                this.txtSearchName.Text = this.txtNewContactLastName.Text;

                //Rebind the contacts grid
                this.gvContacts.DataBind();
            }
            else
            {
                this.lblAddNewContactMessage.Text = "The email address " + this.txtNewContactEmail.Text + " already exists in the database. Please re-enter the correct email address or click <a href=\"Contacts.aspx?email=" + this.txtNewContactEmail.Text + "\">here</a> to view the contact with this email address. You can then associate the contact with this venue from the contact detail screen.";
                this.txtNewContactEmail.Text = string.Empty;
            }
        }
    } 
    protected void btnAddComment_Click(object sender, EventArgs e)
    {
        PlacementManager.NoteComponent oNoteC = new PlacementManager.NoteComponent();
        PlacementManager.Note oNote = new PlacementManager.Note();
        oNote.CreatedBy = User.Identity.Name;
        oNote.DateCreated = DateTime.Now;
        oNote.DateUpdated = DateTime.Now;
        oNote.EntityId = Int32.Parse(this.gvContacts.SelectedValue.ToString());
        oNote.IsActive = true;
        oNote.NoteTypeId = 1;
        oNote.UpdatedBy = User.Identity.Name;
        oNote.NoteText = this.txtAddNewNote.Text;
        oNoteC.Insert(oNote);

        this.gvNotes.DataBind();
        this.txtAddNewNote.Text = string.Empty;
    }
    protected void btnSimpleSearch_Click(object sender, EventArgs e)
    {

    }
    
    #region Helper methods
    public string GetFormattedAddress(string sAddressId)
    {
        int addressId = Int32.Parse(sAddressId);
        if (addressId > 0)
        {
            PlacementManager.AddressComponent oAddressC = new PlacementManager.AddressComponent();
            return oAddressC.GetFormattedAddress(addressId);
        }
        else
        {
            return string.Empty;
        }
    }
    protected string GetIsPrimaryAddress(string addressId)
    {
        string toReturn = string.Empty;

        PlacementManager.LinkContactAddressComponent oLvaC = new LinkContactAddressComponent();
        List<PlacementManager.LinkContactAddress> oLinkList = oLvaC.SelectAllWAddressId(Int32.Parse(addressId), "AddressId");
        if (oLinkList.Count > 0)
        {
            if (oLinkList[0].IsPrimary)
            {
                toReturn = "Primary Address:<br />";
            }
        }
        return toReturn;
    }
    protected bool ShowMakePrimaryAddressButton(string addressId)
    {
        bool toReturn = false;

        PlacementManager.LinkContactAddressComponent oLvaC = new LinkContactAddressComponent();
        List<PlacementManager.LinkContactAddress> oLinkList = oLvaC.SelectAllWAddressId(Int32.Parse(addressId), "AddressId");
        if (oLinkList.Count > 0)
        {
            if (oLinkList[0].IsPrimary)
            {
                toReturn = false;
            }
            else
            {
                toReturn = true;
            }
        }
        return toReturn;
    }
    protected string GetVenueName(string sVenueId)
    {
        PlacementManager.VenueComponent oVenue = new PlacementManager.VenueComponent();
        string s = string.Format("<a href='Venues.aspx?id={1}'>{0}</a>", oVenue.SelectOne(Int32.Parse(sVenueId)).VenueName, oVenue.SelectOne(Int32.Parse(sVenueId)).VenueId.ToString());

        return s;
    }
    protected string GetContactNumber(string sContactNumberId)
    {
        PlacementManager.ContactNumberComponent o = new PlacementManager.ContactNumberComponent();
        return o.GetContactNumberWContactNumberId(Int32.Parse(sContactNumberId));
    }
    protected string GetContactNumberType(string sContactNumberId)
    {
        PlacementManager.ContactNumberComponent oCncC = new PlacementManager.ContactNumberComponent();
        PlacementManager.ContactNumber oContactNumber = oCncC.SelectOne(Int32.Parse(sContactNumberId));

        PlacementManager.ContactNumberTypeComponent oCntC = new PlacementManager.ContactNumberTypeComponent();
        return oCntC.SelectOne(oContactNumber.ContactNumberTypeId).ContactNumberTypeName;
    }
    protected string GetCityState(string sAddressId)
    {
        int addressId = Int32.Parse(sAddressId);
        if (addressId > 0)
        {
            PlacementManager.AddressComponent oAddressC = new PlacementManager.AddressComponent();
            return oAddressC.GetCityState(addressId);
        }
        else
        {
            return string.Empty;
        }
    }
    protected string GetEducatorType(string sEducatorType)
    {
        PlacementManager.EducatorTypeComponent oEducatorTypeC = new EducatorTypeComponent();
        return oEducatorTypeC.SelectOne(Int32.Parse(sEducatorType)).EducatorTypeName;
    }
    #endregion







    protected void gvContacts_DataBound(object sender, EventArgs e)
    {
        if (this.gvContacts.Rows.Count == 0)
        {
            
        }
        else
        {
            
        }
    }
    protected void imgbtnSearch_Click(object sender, ImageClickEventArgs e)
    {

    }
    protected void gvNotes_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        PlacementManager.NoteComponent oNoteC = new NoteComponent();
        PlacementManager.Note oNote = oNoteC.SelectOne(Int32.Parse(this.gvNotes.DataKeys[this.gvNotes.EditIndex].Value.ToString()));

        e.NewValues.Add("CreatedBy", oNote.CreatedBy);
        e.NewValues.Add("DateCreated", oNote.DateCreated);
        e.NewValues.Add("DateUpdated", DateTime.Now);
        e.NewValues.Add("IsActive", oNote.IsActive);
        e.NewValues.Add("EntityId", oNote.EntityId);
        e.NewValues.Add("NoteId", oNote.NoteId);
        e.NewValues.Add("NoteTypeId", oNote.NoteTypeId);
        e.NewValues.Add("UpdatedBy", User.Identity.Name);
    }
    protected void gvNotes_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteNote")
        {
            PlacementManager.NoteComponent oNoteC = new NoteComponent();
            PlacementManager.Note oNote = oNoteC.SelectOne(Int32.Parse(e.CommandArgument.ToString()));
            oNote.IsActive = false;
            oNoteC.Update(oNote);
            this.gvNotes.DataBind();

        }
    }
    protected void btnSaveNote_Click(object sender, EventArgs e)
    {
        if (this.gvContacts.Rows.Count > 0)
        {
            PlacementManager.NoteComponent oNoteC = new PlacementManager.NoteComponent();
            PlacementManager.Note oNote = new PlacementManager.Note();
            oNote.CreatedBy = User.Identity.Name;
            oNote.DateCreated = DateTime.Now;
            oNote.DateUpdated = DateTime.Now;
            oNote.EntityId = Int32.Parse(this.gvContacts.SelectedValue.ToString());
            oNote.IsActive = true;
            oNote.NoteTypeId = 1;
            oNote.UpdatedBy = User.Identity.Name;
            oNote.NoteText = this.txtAddNewNote.Text;
            oNoteC.Insert(oNote);

            this.gvNotes.DataBind();
            this.txtAddNewNote.Text = string.Empty;
        }
    }
    protected void gvContacts_PageIndexChanged(object sender, EventArgs e)
    {
        this.gvContacts.SelectedIndex = 0;
    }
}
